require(["common", "coAjax", "queryString", "hash_routie", "title"], function(jSouper, coAjax, QueryString, hash_routie, title) {

	var queryString = new QueryString(location.hash);
	// console.log(queryString);
	var get_goods_type = queryString.get("id");
	App.set("$Cahce.goods_search_result_type", get_goods_type);
	var get_search_key = queryString.get("q");
	if (!get_search_key) {
		alert("error", "请输入搜索关键字");
	}
	App.set("$Cache.search_key", get_search_key);
	var goods_search_result_url = appConfig.goods.search_with_page_info;
	App.set("$Cache.goods_info.type", "搜索结果");

	//页号
	var current_page_num = ~~queryString.get("page");
	// console.log(current_page_num);
	//每页显示数量
	var goods_pre_num = ~~queryString.get("num") || appConfig.goods_pre_num || 12;
	App.set("config.goods_pre_num", goods_pre_num);
	App.set("$Cache.goods_pre_num", goods_pre_num);
	jSouper.ready(function(argument) {
		App.set("$Cache.current_page_num", current_page_num);
	});
	//获取指定页的商品
	coAjax.get(goods_search_result_url, {
		bus_id: appConfig.bus_id,
		q: get_search_key,
		num: goods_pre_num,
		page: current_page_num
	}, function(result) {
		// console.log("goods:", result.result);
		var info = result.result;
		var goods_list = jSouper.map(info.goods_with_weight, function(goods) {
			return goods.goods;
		});
		var page_info = {
			total_num: info.total_num,
			total_page: info.total_page,
			page: info.page,
			num: info.num
		};
		page_info._number_list = [];
		page_info._number_list.length = info.total_page;
		App.set("goods", goods_list);
		App.set("$Cache.goods_search_result.page_info", page_info);
	});
	/*
	 * 添加到购物车
	 */
	function _get_cart_success(result) {
		var cart_detail = result.result;

		App.set("user.cart_detail", cart_detail);
		App.set("$Cache.cart.total_price", Model.Observer(function() {
			var cart_detail = App.get("user.cart_detail");
			var total_price = 0;
			cart_detail.forEach(function(cart) {
				cart.goods_info.forEach(function(goods_info) {
					total_price += goods_info.goods.price * goods_info.num;
				});
			});
			return total_price;
		}));
		alert("success", "添加成功")
	};

	function _get_cart_error(errorCode, xhr, errorMsg) {
		console.log("%c" + errorCode + ": " + errorMsg, "color:orange;font-size:14px; text-shadow: 0 1px 0 #ccc;");
		alert("error", errorMsg);
	};
	App.set("$Event.goods_search_result.add_to_cart", function(e, vm) {
		var cart_item = {
			goods_id: vm.get("_id"),
			num: 1
		};
		if (App.get("loginer")) {
			coAjax.post(appConfig.user.cart, cart_item, _get_cart_success, _get_cart_error);
		} else {
			var cache_cart = LS.get("$Cache.cart");
			try {
				cache_cart = JSON.parse(cache_cart);
			} catch (e) {
				console.error(e)
			}
			if (!(cache_cart instanceof Array)) {
				cache_cart = [];
			}
			cache_cart.push(cart_item);
			LS.set("$Cache.cart", JSON.stringify(cache_cart));
		}
	});
});